// 帧动画Image
import 'package:flutter/material.dart';

class VoiceAnimationImage extends StatefulWidget {
  final double width;
  final double height;
  int interval = 200;
  bool isStop = false;
  var callStart;
  VoiceAnimationImageState voiceAnimationImageState;

  VoiceAnimationImage({this.width, this.height, this.isStop, this.interval});

  @override
  State<StatefulWidget> createState() {
    voiceAnimationImageState = VoiceAnimationImageState();
    return voiceAnimationImageState;
  }

  start() {
    voiceAnimationImageState.start();
  }

  stop() {
    voiceAnimationImageState.stop();
  }
}

class VoiceAnimationImageState extends State<VoiceAnimationImage>
    with SingleTickerProviderStateMixin {
  // 动画控制
  Animation<double> _animation;
  AnimationController _controller;
  int interval = 200;
  List<String> _assetList = [];

  @override
  void initState() {
    super.initState();
    _assetList.add("images/bofang2.png");
    _assetList.add("images/bofang1.png");
    _assetList.add("images/bofang.png");
    if (widget.interval != null) {
      interval = widget.interval;
    }
    final int imageCount = _assetList.length;
    final int maxTime = interval * imageCount;

    // 启动动画controller
    _controller =
        new AnimationController(vsync:this,duration: Duration(milliseconds: maxTime));
    _controller.addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.completed) {
        _controller.forward(from: 0.0); // 完成后重新开始
      }
    });

    _animation = new Tween<double>(begin: 0, end: imageCount.toDouble())
        .animate(_controller)
          ..addListener(() {
            setState(() {});
          });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  stop() {
    _controller.stop();
  }

  start() {
    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isStop) {
      start();
    } else {
      stop();
    }
    int ix = _animation.value.floor() % _assetList.length;
    List<Widget> images = [];
    // 把所有图片都加载进内容，否则每一帧加载时会卡顿
    for (int i = 0; i < _assetList.length; ++i) {
      if (i != ix) {
        images.add(Image.asset(
          _assetList[i],
          width: 0,
          height: 0,
        ));
      }
    }
    images.add(Image.asset(
      _assetList[ix],
      width: widget.width,
      height: widget.height,
    ));
    return Stack(alignment: AlignmentDirectional.center, children: images);
  }
}
